package com.example.daxiguaforharmony.game.core.loader;

import com.example.daxiguaforharmony.game.core.GameError;
import com.example.daxiguaforharmony.game.core.utils.Log;

import java.util.ArrayList;

public class GameLoader {

    public static class Event {
        public static String LOAD_START = "GAME_LOAD_START";
        public static String LOAD_COMPLETE = "GAME_LOAD_COMPLETE";
        public static String LOAD_PROGRESS = "GAME_LOAD_PROGRESS";
        public static String LOAD_ERROR = "GAME_LOAD_ERROR";
    }

    private ArrayList<GameLoadStep> _loadQueue = null;
    private int _loadIndex = 0;
    private float _progress = 0f;

    public GameLoader() {
    }

    public void start() {
        if (this._loadQueue.size() > 0) {
            this.emit(GameLoader.Event.LOAD_START, null, 0);
            this.executeNextStep();
        } else {
            this.emit(GameLoader.Event.LOAD_COMPLETE, null, 100);
        }
    }

    public void addStep(GameLoadStep step) {
        if (step != null) {
            this._loadQueue.add(step);
        }
    }

    public void removeSteps() {
        this._loadQueue.clear();
        this._loadIndex = 0;
        this._loadIndex = 0;
    }

    public void onStepProgress(float progress) {
        progress = this._progress + progress;
        this.emit(GameLoader.Event.LOAD_PROGRESS, null, progress);
    }

    public void onStepCompleted(float progress) {
        this._progress += progress;
        this.emit(GameLoader.Event.LOAD_PROGRESS, null, this._progress);
        GameLoadStep currStep = this._loadQueue.get(this._loadIndex);
        if (currStep != null) {
            if (!currStep.isExecuteComplete()) {
                Log.warning("GameLoader.onStepCompleted: 当前步骤没有完成，但是被调用完成了！");
            }
            currStep.destory();
            currStep = null;
        }
        this._loadIndex += 1;
        if (this._loadIndex == this._loadQueue.size()) {
            this.emit(GameLoader.Event.LOAD_COMPLETE, null, 100);
        } else if (this._loadIndex > this._loadQueue.size()) {
            Log.error("GameLoader: step load error! loadIndex = " + this._loadIndex + ", totalIndex" + this._loadQueue.size());
        } else {
            this.executeNextStep();
        }
    }

    public void onStepFail(GameError error) {
        this.emit(GameLoader.Event.LOAD_ERROR, error, -1);
    }

    private void executeNextStep() {
        GameLoadStep step = this._loadQueue.get(this._loadIndex);
        Log.info("GameLoader: step = " + this._loadIndex + ", stepName = " + step.getStepName());
        step.setLoadIndex(this._loadIndex);
        step.setGameLoader(this);
        step.execute();
    }

    private void emit(String event, GameError error, float progress) {

    }
}
